<template>
  <div class="q-pa-md">
    <input-dialog
      title="新增作业方案"
      :fields="addPlanFields"
      :dialog-show-value="isShowAddPlanDialog"
      defaultButtonName="新增计划"
      @close="closeAddPlanDialog"
      @onConfirm="addPlan"
    ></input-dialog>

    <input-dialog
      title="修改作业方案"
      :fields="modifyPlanFields"
      :dialog-show-value="isShowModifyPlanDialog"
      defaultButtonName="修改方案"
      @close="closeModifyPlanDialog"
      @onConfirm="confirmModifyPlan"
    ></input-dialog>

    <action-list ref="actionListDialog"></action-list>
    <q-table
      title="作业方案列表"
      :rows="plans"
      :columns="columns"
      row-key="name"
      flat
      bordered
      style="height: 100%"
      :filter="filter"
      :rows-per-page-options="[8]"
      rows-per-page-label="每页记录数"
    >
      <!--顶部插槽-->
      <template v-slot:top-right>
        <q-input
          borderless
          dense
          debounce="300"
          v-model="filter"
          placeholder="搜索方案"
          class="rounded-borders bg-grey-4"
          style="padding: 0 10px"
        >
          <template v-slot:append>
            <q-icon name="search" />
          </template>
        </q-input>
        <q-btn
          round
          color="primary"
          icon="add"
          style="margin-left: 20px"
          @click="addPlanClick"
        />
      </template>
      <!--列名插槽-->
      <template v-slot:header="props">
        <q-tr :props="props" class="my-header">
          <q-th v-for="col in props.cols" :key="col.name" :props="props">
            {{ col.label }}
          </q-th>
        </q-tr>
      </template>
      <!--数据插槽-->
      <template v-slot:body="props">
        <q-tr :props="props">
          <q-td key="title" :props="props"> {{ props.row.name }}</q-td>
          <q-td key="type" :props="props"> {{ props.row.type }}</q-td>
          <q-td key="desc" :props="props"> {{ props.row.description }}</q-td>
          <q-td key="actionManagement" :props="props">
            <q-btn
              align="around"
              size="sm"
              color="primary"
              label="动作管理"
              icon="accessibility_new"
              @click="actionManagerClick(props.rowIndex)"
            />
          </q-td>
          <q-td key="modify" :props="props">
            <q-btn
              align="around"
              size="sm"
              color="primary"
              label="修改"
              icon="edit"
              @click="modifyPlanClick(props.rowIndex)"
            />
          </q-td>
          <q-td key="delete" :props="props">
            <q-btn
              align="around"
              size="sm"
              color="red-10"
              label="删除"
              icon="delete"
              @click="deletePlan(props.rowIndex)"
            />
          </q-td>
        </q-tr>
      </template>
    </q-table>
  </div>
</template>

<script setup>
import { api } from "boot/axios";
import InputDialog from "components/dialog/InputDialog.vue";
import { useQuasar } from "quasar";
import { useAPIStore } from "stores/api";
import { computed, onMounted, ref, toRaw, watch } from "vue";
import ActionList from "./ActionList.vue";
const $q = useQuasar();
const filter = ref("");
const plans = ref();
const isShowAddPlanDialog = ref(false);
const isShowModifyPlanDialog = ref(false);
const columns = [
  {
    name: "title",
    required: true,
    label: "标题",
    align: "left",
    field: (row) => row.name,
    format: (val) => `${val}`,
  },
  { name: "type", align: "left", label: "类型", field: (row) => row.type },
  {
    name: "desc",
    align: "left",
    label: "描述",
    field: (row) => row.description,
  },
  { name: "actionManagement", align: "center", label: "动作管理" },
  { name: "modify", align: "center", label: "修改方案" },
  { name: "delete", align: "center", label: "删除方案" },
];
const typeName = {
  single: "单机任务",
  multiple: "多机协同任务",
};
const modifyPlanFields = ref([
  {
    key: "planName",
    name: "计划名称",
    value: "",
    required: true,
  },
  {
    key: "planType",
    name: "方案类型",
    value: "",
    required: true,
    type: "select",
    options: [
      {
        label: "多机协同任务",
        value: "多机协同任务",
      },
      {
        label: "单机任务",
        value: "单机任务",
      },
    ],
  },
  {
    key: "executionDevice",
    name: "执行设备",
    value: "",
    required: true,
    type: "select",
    options: [],
  },
  {
    key: "planDesc",
    name: "作业描述",
    value: "",
    type: "textarea",
  },
]);
const actionListDialog = ref();
const currentModifyPlan = ref();
watch(
  modifyPlanFields.value,
  (fields) => {
    modifyPlanFields.value[2].isHidden = fields[1].value !== "单机任务";
    if (currentModifyPlan.value) {
      currentModifyPlan.value.name = fields[0].value;
      currentModifyPlan.value.type =
        fields[1].value === "单机任务" ? "single" : "multiple";
      currentModifyPlan.value.device = fields[2].value;
      currentModifyPlan.value.description = fields[3].value;
    }
  },
  {
    deep: true,
  }
);
const addPlanFields = ref([
  {
    key: "planName",
    name: "作业名称",
    value: "",
    required: true,
  },
  {
    key: "planDesc",
    name: "作业描述",
    value: "",
    type: "textarea",
  },
]);

onMounted(() => {
  getPlans();
  getDevices();
});

/**
 * 获取方案列表数据
 */
function getPlans() {
  api
    .get(useAPIStore().centerUrl + "plan/all")
    .then((rs) => {
      plans.value = rs.data.map((value) => {
        value.type = typeName[value.type];
        return value;
      });
    })
    .catch((e) => {
      $q.notify({ type: "negative", message: "方案加载失败", position: "top" });
    });
}

/**
 * 获取所有设备数据
 */
function getDevices() {
  api.get(useAPIStore().centerUrl + "configs/all").then((rs) => {
    modifyPlanFields.value[2].options = rs.data.map((item) => {
      return item.id;
    });
  });
}

/**
 * 右上角添加按钮点击事件
 */
function addPlanClick() {
  isShowAddPlanDialog.value = true;
}

/**
 * 关闭新增作业方案弹框
 */
function closeAddPlanDialog() {
  isShowAddPlanDialog.value = false;
}

/**
 * 关闭修改作业方案弹框
 */
function closeModifyPlanDialog() {
  isShowModifyPlanDialog.value = false;
}

const planParams = computed(() => {
  const obj = {};
  obj.name = addPlanFields.value[0].value;
  obj.description = addPlanFields.value[1].value;
  return obj;
});

/**
 * 新增方案
 */
function addPlan() {
  for (let i = 0; i < addPlanFields.value.length; i++) {
    if (addPlanFields.value[i].required && !addPlanFields.value[i].value) {
      $q.notify({
        message: `${addPlanFields.value[i].name}不能为空`,
        type: "negative",
        position: "top",
      });
      return;
    }
  }
  api.post(useAPIStore().centerUrl + "plan", planParams.value).then((rs) => {
    if (rs.status === 200) {
      $q.notify({
        message: "巡检方案创建成功",
        type: "positive",
        position: "top",
      });
      getPlans();
      isShowAddPlanDialog.value = false;
      addPlanFields.value.forEach((field) => {
        field.value = "";
      });
    } else {
      $q.notify({ message: "方案创建失败", type: "negative", position: "top" });
    }
  });
}

/**
 * 删除方案
 * @param index
 */
function deletePlan(index) {
  $q.dialog({
    title: "删除方案",
    message: `是否要删除${plans.value[index].name}该方案？`,
    cancel: true,
    persistent: true,
  }).onOk(() => {
    api
      .delete(useAPIStore().centerUrl + "plan/" + plans.value[index].id)
      .then(() => {
        plans.value.splice(index, 1); // 先移除本地的再重新获取一遍最新数据
        getPlans();
        $q.notify({
          message: "方案删除成功",
          type: "positive",
        });
      });
  });
}

/**
 * 修改方案按钮点击事件，点击弹出修改方案弹框
 * @param index
 */
function modifyPlanClick(index) {
  currentModifyPlan.value = JSON.parse(
    JSON.stringify(toRaw(plans.value[index]))
  );
  if (currentModifyPlan.value.type !== "单机任务") {
    // 如果是单机任务，不需要显示执行设备
    modifyPlanFields.value[2].isHidden = true;
  }
  modifyPlanFields.value[0].value = currentModifyPlan.value.name; // 方案名称
  modifyPlanFields.value[1].value = currentModifyPlan.value.type; // 方案类型
  modifyPlanFields.value[2].value = currentModifyPlan.value.device; // 执行设备
  modifyPlanFields.value[3].value = currentModifyPlan.value.description; // 作业描述
  isShowModifyPlanDialog.value = true;
}

/**
 * 确认修改方案
 */
function confirmModifyPlan() {
  if (currentModifyPlan.value.type === "多机协同任务") {
    currentModifyPlan.value.device = null;
  }
  api
    .put(useAPIStore().centerUrl + "plan", currentModifyPlan.value)
    .then(() => {
      isShowModifyPlanDialog.value = false;
      $q.notify({
        message: "方案修改成功",
        type: "positive",
        position: "top",
      });
      getPlans();
    });
}

/**
 * 弹出动作管理弹框
 * @param {*} index
 */
function actionManagerClick(index) {
  actionListDialog.value.showActionListDialog(
    plans.value[index].device,
    plans.value[index].id
  );
}
</script>

<style scoped>
.my-header th {
  color: black;
  font-weight: bold;
  font-size: 13px;
  position: sticky;
  z-index: 1;
  background: white;
}

.my-header:first-child th {
  top: 0;
}
</style>
